
//
//  HZOAythViewController.swift
//  HansWeibo
//
//  Created by Hans on 16/8/10.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit
import SVProgressHUD
class HZOAythViewController: UIViewController {

    
    
    override func loadView() {
        view = webView
        //判断是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else {
            return
        }
        
        webView.delegate = self
        
        
        // absoluteString  把url转换成字符串
        print(url.absoluteString)
        
        //实例化request
        let request = NSURLRequest(URL: url)
        //加载request
        webView.loadRequest(request)
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    //MARK: - 监听方法
    // 取消
    @objc private func cancelAction(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    // 自动填充
    @objc private func autofillAction(){
        
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    //MARK: -设置视图
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        
    }
    
    //MARK: - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofillAction")
        navigationItem.title = "微博登录"
    }
    
    
    // MARK - 懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
}

extension HZOAythViewController:UIWebViewDelegate{
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    /*
        监听webView 将要加载的request
            返回值  如果不实现默认返回true
            如果返回 false  停止加载request
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 记载的urlString
//        let urlString1 = request.URL?.absoluteString
        // 判断urlString是否为nil
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            print(urlString)
            // query 请求参数
            // 判断是否为nil
            if let query = request.URL?.query {
                // 获取code
                let code = query.substringFromIndex("code=".endIndex)
                
                print(code)
                
                HZUserAccountViewModel.sharedTools.setUserAccount(code, finish: { (isSusses) in
                    
                    if  !isSusses {
                        print("请求失败")
                        return
                    }
                    
                    print("请求成功")
//                    let result = HZUserAccountViewModel.sharedTools.userAccount
//                    print(result)
                    
                    self.dismissViewControllerAnimated(false, completion: { 
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(NSNOTIFICATIONCENTER, object: "oauth")
                    })
                    
                    
                })
                return false
            }
        }
       return true
    }
}




// MARK 请求数据
extension HZOAythViewController{
    
    // 被抽取到ViewModel
    
    // 获取授权
//    func setUserAccount(code: String){
//        //发送请求
//        HZNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) in
//            
//            guard let res = response as? [String : AnyObject] else {
//                print(response)
//                return
//            }
//            
//            let userAccont = HZUserAccessModel(dict: res)
//            print(userAccont)
//            self.getuserInfo(userAccont)
//            }) { (error) in
//                print("失败1\(error)")
//        }
//    }
//    
//    
//    //请求个人信息
//    func getuserInfo(userAccount: HZUserAccessModel){
//        //发送请求
//        HZNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
//            
//            guard let res = response as? [String:AnyObject] else {
//                return
//            }
//            //赋值
//            userAccount.screen_name = res["screen_name"] as? String
//            userAccount.avatar_large = res["avatar_large"] as? String
//            
//            print(userAccount)
//            }) { (error) in
//                print("失败2\(error)")
//        }
//    }

}
